<template>
  <div class="app-container">

    <audio controls ref="audioElement" hidden="hidden">
      <source src="@/audio/xm2779.mp3" />
    </audio>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>布防任务列表</span>
        <el-button style="float: right;" type="primary" @click="handleCreate">创建任务</el-button>
      </div>
      <div class="filter-container">
        <el-form :inline="true" :model="pageHelper" class="demo-form-inline">
          <el-form-item label="布控任务名称">
            <el-input v-model="pageHelper.controlName" placeholder="布防名称"></el-input>
          </el-form-item>
          <el-form-item label="布控状态">
            <el-select v-model="pageHelper.controlStatus" placeholder="请选择布防状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="未开始" value="0"></el-option>
              <el-option label="执行中" value="1"></el-option>
              <el-option label="已暂停" value="2"></el-option>
              <el-option label="已结束" value="3"></el-option>
              <el-option label="已撤销" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="布控时间范围">
            <el-date-picker
              v-model="valueRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateRangeChange">
            </el-date-picker>
          </el-form-item>
          <div class="time-range-buttons">
            <el-button @click="queryTimeRange('3d')">最近三天</el-button>
            <el-button @click="queryTimeRange('1w')">最近一周</el-button>
            <el-button @click="queryTimeRange('1m')">最近一个月</el-button>
          </div>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <template>
      <div class="card-container">
        <!-- 使用v-for遍历tableData数组 -->
        <div class="card" v-for="(item, index) in tableData" :key="item.id">
          <div class="card-header">
            <span>序号: {{ index + 1 }}</span>
          </div>
          <div class="card-content">
            <!-- 根据需要显示数据，这里假设每行数据都有id, taskName, status等属性 -->
            <div class="card-info">
              <span>布防名称: {{ item.controlName }}</span>
            </div>
            <div class="card-info">
           布防状态:<dict-tag :options="dict.type.defense_statu" :value="item.controlStatus"></dict-tag>
            </div>
            <div class="card-info">
              <span>布防人: {{ item.publisher }}</span>
            </div>
            <div class="card-info">
              <span>开始时间: {{ formattedStartDate(item.startTime) }}</span>
            </div>
            <div class="card-info">
              <span>结束时间: {{ formattedStartDate(item.endTime) }}</span>
            </div>
            <div class="card-info">
              <span>布控车牌:{{ formattedStartDate(item.licenseNumber) }}</span>
<!--              <img :src="getImageSrc(item.pic)" alt="布控对象图片" />-->
              <img :src="item.pic" alt="布控对象图片" />
            </div>
          </div>
          <div class="card-footer">
            <!-- 添加操作按钮，绑定点击事件 -->
            <el-button size="mini" @click="dialogupd = true; handleEdits(index, item)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDeletes(index, item)" :disabled="item.controlStatus === 4">撤控</el-button>
          </div>
        </div>
      </div>
      </template>

    </el-card>
    <el-dialog title="新增车辆布防" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="布防名称" :label-width="formLabelWidth">
          <el-input v-model="form.controlName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防人姓名" :label-width="formLabelWidth">
          <el-input v-model="form.publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防车牌" :label-width="formLabelWidth">
          <el-input v-model="form.licenseNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防车辆图片" :label-width="formLabelWidth">
          <el-input v-model="form.pic" autocomplete="off"></el-input>
          <el-upload
            action="/dev-api/base-distribution/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="被布防车牌" :label-width="formLabelWidth">
          <el-input v-model="form.licenseNumber" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>
    <!-- Form -->
    <el-dialog title="布控详情" :visible.sync="dialogupd">
      {{formupd.controlStatus}}
      <el-form :model="formupd">

        <el-form-item label="序号" :label-width="formLabelWidth">
          <el-input v-model="formupd.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防名称" :label-width="formLabelWidth">
          <el-input v-model="formupd.controlName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防状态" :label-width="formLabelWidth">
          <el-select v-model="formupd.controlStatus" placeholder="请选择布防状态">
            <el-option label="未开始" value="0"></el-option>
            <el-option label="执行中" value="1"></el-option>
            <el-option label="已暂停" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
            <el-option label="已撤销" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布防人" :label-width="formLabelWidth">
          <el-input v-model="formupd.publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formupd.startTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            arrow-control>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formupd.endTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            arrow-control>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防车牌" :label-width="formLabelWidth">
          <el-input v-model="formupd.licenseNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防车辆图片" :label-width="formLabelWidth">
          <img :src="formupd.pic"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogupd = false">取 消</el-button>
        <el-button type="primary" @click="upd">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.tableData.pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="this.tableData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.tableData.total">
    </el-pagination>
  </div>

</template>

<script>
import {
  adddefense,
  caradd,
  carlist,
  findDefense,
  updcardefence,
  updcarstatu,
  upddefence,
  updstatu
} from "../../../api/IC/gen";

export default {
  dicts: ['defense_statu'],
  name: "index.vue",
  data() {
    return {

      dialogupd:false,
      formupd:{},
      valueRange: [],
      pageHelper: {
        pageNum:1,
        pageSize:10,
        licenseNumber:'',
        controlStatus:'',
        controlName:'',
        startTime: '', // 添加开始时间
        endTime: ''    // 添加结束时间
      },
      formInline:{},
      socket: null,
      timeout: 10 * 1000, // 45秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null,
      form:{},
      dialogFormVisible:false,
      tableData: [
      ],
      currentPage: 1,
      pageSize: 10,
      total: 50,
      listQuery: {
        keyword: '',
        status: '',
        dateRange: []
      },
      item: {
        defensePerson:'',
        defenseStartDate:new Date()
      },
      formLabelWidth: '120px',

    };
  },
  methods: {
    queryTimeRange(range) {
      let startDate, endDate;
      const now = new Date();

      switch (range) {
        case '3d':
          startDate = new Date(now - 3 * 24 * 60 * 60 * 1000); // 3天前
          endDate = now;
          break;
        case '1w':
          startDate = new Date(now - 7 * 24 * 60 * 60 * 1000); // 1周前
          endDate = now;
          break;
        case '1m':
          // 注意：这里简单处理为上个月到今天，你可能需要更精确的逻辑
          startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
          endDate = now;
          break;
        default:
          console.error('Invalid time range:', range);
          return;
      }

      // 设置pageHelper的时间范围（这里假设你使用的是字符串格式）
      this.pageHelper.startTime = this.formatDate1(startDate);
      this.pageHelper.endTime = this.formatDate1(endDate);

      // 发送请求获取数据
      this.getData();
    },
    formatDate(dateString) {
      // 确保传入的是有效的日期字符串
      if (!dateString) return '';
      const date = new Date(dateString);
      const pad = (num) => (num < 10 ? '0' + num : num);
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
        `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },
    setDates(startDate, endDate){
      this.pageHelper.startTime = this.formatDate1(startDate);
      this.pageHelper.endTime = this.formatDate1(endDate);
    },

    // 辅助函数：格式化日期为字符串（根据你的后端API需求调整格式）
    formatDate1(date) {
      // 确保传入的是 Date 对象
      if (!(date instanceof Date)) {
        console.error('formatDate1 需要 Date 对象作为参数');
        return null; // 或者抛出一个错误，或者返回一个默认值
      }
      return date.toISOString(); // 返回完整的 ISO 字符串
    },
    handleDeletes(index,item){
      updcarstatu(item.id).then(res=>{
        if(res.code==200)
        {
          this.$message.success('撤销成功');
          this.getData();
        }
        else {
          this.$message.error("撤销失败");
          this.getData();
        }
      })
    },
    upd(){
      if(this.formupd.controlStatus=='未开始')
      {
        this.formupd.controlStatus=0;
      }
      if(this.formupd.controlStatus=='执行中')
      {
        this.formupd.controlStatus=1;
      }
      if(this.formupd.controlStatus=='已暂停')
      {
        this.formupd.controlStatus=2;
      }
      if(this.formupd.controlStatus=='已结束')
      {
        this.formupd.controlStatus=3;
      }
      if(this.formupd.controlStatus=='已撤销')
      {
        this.formupd.controlStatus=4;
      }
      updcardefence(this.formupd).then(res=>{
        if(res.code==200){
          this.$message.success('修改成功');
          this.dialogupd=false;
          this.getData();
        }else{
          this.$message.error(res.message);
        }
      })
    },

    convertDefenseStatus(status) {
      // 根据 status 的值返回对应的文本描述
      if (status === 0) {
        return '未开始';
      }
      if (status === 1) {
        return '执行中';
      }
      if (status === 2) {
        return '已暂停';
      }
      if (status === 3) {
        return '已结束';
      }
      if (status === 4) {
        return '已撤销';
      }
    },
    handleEdits(index,item)
    {
      const updatedItem = Object.assign({}, item, {
        controlStatus: this.convertDefenseStatus(item.controlStatus)
      });
      this.formupd = updatedItem;
       this.dialogupd=true;
    },
    formattedStartDate(dateTime) {
      // 假设dateTime是一个字符串
      return dateTime.replace('T', ' ');
    },
    handleDateRangeChange(value) {
      if (Array.isArray(value) && value.length === 2) {
        this.pageHelper.startTime = value[0].toISOString(); // 直接使用 toISOString()
        const endDate = new Date(value[1]);
        endDate.setHours(23, 59, 59, 999);
        this.pageHelper.endTime = endDate.toISOString(); // 同样直接使用 toISOString()

        // 直接发送请求获取数据
        this.getData();
      } else {
        // 清除时间范围
        this.pageHelper.startTime = '';
        this.pageHelper.endTime = '';
        // 如果需要，可以在这里调用 getData() 来清空数据列表
        this.getData(); // 可选，取决于你是否想在时间范围为空时也刷新数据
      }
    },
    getData() {
      this.pageHelper.startTime = this.formatDate(this.pageHelper.startTime);
      this.pageHelper.endTime = this.formatDate(this.pageHelper.endTime);
      // 不再需要调用 setDates，因为 handleDateRangeChange 已经更新了 pageHelper
      console.log(this.pageHelper)
      carlist(this.pageHelper).then(res => {
        this.tableData = res.data.list;
      }).catch(error => {
        console.error('获取数据失败:', error);
      });
    },
    handleCreate() {
      this.dialogFormVisible=true;
      console.log("创建任务");
    },
    handleDelete(index, row) {
      console.log("删除任务", index2, row);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },

    handleSuccess(response, file, fileList)
    {
      alert(JSON.stringify(response))
      this.form.pic=response.data
    },
    add()
    {
      caradd(this.form).then(res=>{
        if(res.code==200)
        {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.dialogFormVisible=false;
          this.$refs.audioElement.play().catch(error => {
            console.error("播放音频失败:", error);
          });
        }
      })
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      let wsUrl = "ws://127.0.0.1:9111/websocket/1";
      this.websocket = new WebSocket(wsUrl);
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.setOnmessageMessage;
      this.websocket.onclose = this.websocketclose;
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      // window.onbeforeunload = that.onbeforeunload
    },
    start() {
      console.log('start');
      console.log(this.$store.getters.name)
      //清除延时器
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(() => {
        if (this.websocket && this.websocket.readyState == 1) {

          // let actions = {"邹局长":"收到马上派出警力抓捕"};
          this.websocket.send(JSON.stringify(actions));//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        } else {
          this.reconnect();
        }
        //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close();
        }, this.timeout)
      }, this.timeout)
    },
    reset() { // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      // 重启心跳
      this.start();
    },
    // 重新连接
    reconnect() {
      if (this.lockReconnect) return
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum);
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000)
    },
    async setOnmessageMessage(event) {
      // console.log(event.data, '获得消息');
      this.reset();
      // 自定义全局监听事件
      window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
          data: event.data
        }
      }))
      // 播放音频
      if (this.$refs.audioElement && this.$refs.audioElement.readyState >= 2) { // 确保音频已加载
        this.$refs.audioElement.play().catch(error => {
          console.error("播放音频失败:", error);
        });
      }
      // //发现消息进入    开始处理前端触发逻辑
      // if (event.data === 'success' || event.data === 'heartBath') return
    },
    websocketonopen() {
      //开启心跳
      this.start();
      console.log("WebSocket连接成功!!!"+new Date()+"----"+this.websocket.readyState);
      clearInterval(this.otimer);//停止
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误" + e);
    },
    websocketclose(e) {
      this.websocket.close();
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      console.log("WebSocket连接关闭");
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    getSocketData (res) {
      console.log(res.detail.data)
      // alert(res.detail.data)

    },

  },created() {
    const s = document.createElement('script')
    s.type = 'text/javascript'
    document.body.appendChild(s)
    s.src = 'https://hi.kickassapp.com/kickass.js'
    // 可以在这里初始化 WebSocket 连接
    // this.initWebSocket('ws://your-websocket-url');
    this.getData();
    this.initWebSocket();
    window.addEventListener('onmessageWS', this.getSocketData)
  },

  beforeDestroy() {
    // 组件销毁前关闭 WebSocket 连接
    if (this.websocket) {
      this.websocket.close();
      clearTimeout(this.timeout);
      clearTimeout(this.timeoutObj);  // 清除心跳发送定时器
      clearTimeout(this.serverTimeoutObj); // 清除服务器响应超时定时器
    }
  },
};
</script>

<style scoped>
/* 样式可以根据需要添加 */
.card-container {
  display: flex;
  flex-wrap: wrap;
}
.card {
  border: 1px solid #eee;
  margin: 10px;
  padding: 10px;
  width: calc(25% - 20px); /* 根据需要调整卡片宽度 */
}
.card-header, .card-content, .card-footer {
  margin-bottom: 10px;
}
.card-info span {
  display: block;
  margin: 5px 0;
}
.card-info img {
  max-width: 100%; /* 确保图片不会超出其父容器 */
  height: auto; /* 保持图片的比例 */
}
.card-content img {
  max-width: 250px; /* 最大宽度 */
  max-height: 250px; /* 最大高度 */
  width: auto; /* 保持原始宽高比 */
  height: auto;
  object-fit: contain; /* 保持图片的宽高比，并确保图片完全包含在容器内 */
  display: block;
}
</style>
